package cn.lxh.ymcc.consumer;

import cn.lxh.ymcc.domain.MessageSms;
import cn.lxh.ymcc.dto.MessageSmsDto;
import cn.lxh.ymcc.service.IMessageSmsService;
import cn.lxh.ymcc.dto.MessageSmsDto;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;


/**
 * 推送短信的消费者
 */
@Component
@RocketMQMessageListener(
        consumerGroup="message-sms-group",
        topic="course-topic",
        selectorExpression="course-tag"
)
@Slf4j
public class MessageSmsConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if(body == null || body.length ==0){
            return;
        }
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        MessageSmsDto smsDto = JSONObject.parseObject(jsonStr, MessageSmsDto.class);
        //保存数据到mysql
        saveMessageSms(smsDto);
        //调用发送短信接口发送短信  批量一起发
        log.info("发送消息成功："+smsDto.getTitle());
    }

    private void saveMessageSms(MessageSmsDto dto) {
//        Date date = new Date();
//        dto.getUsers().forEach(user->{
////            MessageSms messageSms = new MessageSms();
//            BeanUtils.copyProperties(dto,messageSms);
//            messageSms.setUserId(user.getId());
//            messageSms.setSendTime(date);
//            messageSmsService.insert(messageSms);
//        });
    }
}